/**
 * 抖音店铺评分数据记录侧边栏组件
 */

import { StyleProvider } from "@ant-design/cssinjs"
import { FormOutlined } from "@ant-design/icons"
import cssText from "data-text:~/assets/css/dataScreenV2.css"
import antdResetCssText from "data-text:antd/dist/reset.css"
import ky from "ky"
import moment from "moment"
import type {
  PlasmoCSConfig,
  PlasmoGetInlineAnchor,
  PlasmoGetOverlayAnchor,
  PlasmoGetShadowHostId
} from "plasmo"
import React, { useEffect, useState } from "react"

import { usePort } from "@plasmohq/messaging/hook"
import { useStorage } from "@plasmohq/storage/dist/hook"

import { ThemeProvider } from "~theme"
import DyShopScoreDataDetailModal from "~ui_components/DyShopScoreDataDetailModal"
import { _callApi } from "~utils/tools"

// 注入配置
export const config: PlasmoCSConfig = {
  matches: [
    // 视频号微信小店商家体验分页面
    "https://store.weixin.qq.com/shop/setting/rate*"
  ],
  run_at: "document_start",
  all_frames: true
}

// 注入样式
export const getStyle = () => {
  const style = document.createElement("style")
  style.textContent = cssText + antdResetCssText
  return style
}

// 注入的shadow dom的id
export const HOST_ID = "wx-shop-score-tool"
export const getShadowHostId: PlasmoGetShadowHostId = () => HOST_ID

// export const getRootContainer = () => document.getElementById("app")
export const getOverlayAnchor: PlasmoGetOverlayAnchor = async () => {
  return document.querySelector("micro-app")
}

// 组件定义
const WxShopScoreToolbar: React.FC = () => {
  // 请求biz
  const [bizMagic, setBizMagic] = useState<string>("")
  // 评分数据处理port
  const scoreData = usePort("wxShopScoreData")
  // 数据完整性百分比
  const [dataCompleteRate, setDataCompleteRate] = useState("0")
  // 用户是否登录
  const [userLogin] = useStorage("isLogin", false)
  const [showDetailModal, setShowDetailModal] = useState<boolean>(false)
  // 异常信息记录
  const [exceptionTxt, setExceptionTxt] = useState("")

  // 数据请求方法
  const fetchScoreData = async (params: any) => {
    /**
     * 从目标网页中拦截请求标头，获取biz_magic参数
     * 可以伪造请求，获取数据
     */
    try {
      // 地址
      const url =
        "https://store.weixin.qq.com/shop-faas/statistic/cgi/search?token=&lang=zh_CN"
      // 请求, 不用写header
      const response = await fetch(url, {
        method: "POST",
        body: JSON.stringify(params),
        headers: {
          "Content-Type": "application/json",
          "potter-scene": "weixinShop",
          biz_magic: bizMagic,
          mcn_magic: "",
          talent_magic: "",
          wecom_magic: ""
        }
      })
      return await response.json()
    } catch (e) {
      return {}
    }
  }

  // 网络请求拦截事件响应
  // window hijackEvent响应方法
  const eventFunc = (
    event: CustomEvent<{
      url: string
      params: any
      response: any
      headers: any
    }>
  ) => {
    // api地址过滤
    if (event.detail.headers["biz_magic"]) {
      setBizMagic(event.detail.headers["biz_magic"])
    }
  }

  // 获取数据键值总量
  const getKeysCount = async () => {
    const { data } = await _callApi("getKeysCountForDss", { shop_type: "wx" })
    scoreData.send({ action: "setKeys", data: data || 0 })
  }

  // 挂载事件监听
  useEffect(() => {
    // 获取数据键总量
    getKeysCount().then()
    // // 挂载ui到服务
    scoreData.send({ action: "clear" })
    // // 监听hijackEvent事件
    window.addEventListener("hijackEvent", eventFunc)
    return () => {
      // 卸载事件监听
      window.removeEventListener("hijackEvent", eventFunc)
    }
  }, [])

  // 数据抓取按钮触发方法
  const handleCaptureData = async () => {
    setExceptionTxt("")
    // 检查是否有biz_magic
    if (bizMagic === "") {
      setExceptionTxt("没法获取数据，缺失关键参数! 请联系客服!")
      return
    }
    // 循环发送请求，抓取数据到后端处理
    const paramsList = [
      // 整体数据
      {
        days: 14,
        scoreTypeList: [11, 12, 13, 14, 1000]
      },
      // 商品体验 L2
      {
        days: 14,
        scoreTypeList: [70, 64, 1000]
      },
      // 服务体验 L2
      {
        days: 14,
        scoreTypeList: [75, 76, 77, 67, 68, 69, 1000]
      },
      // 物流体验 L2
      {
        days: 14,
        scoreTypeList: [72, 73, 71, 105, 74, 78, 1000]
      },
      // 商品体验 L3
      {
        days: 7,
        scoreTypeList: [79, 80]
      },
      {
        days: 7,
        scoreTypeList: [82, 81]
      },
      // 物流体验 L3
      {
        days: 7,
        scoreTypeList: [103, 84]
      },
      // 服务体验 L3
      {
        days: 7,
        scoreTypeList: [88, 89]
      },
      {
        days: 7,
        scoreTypeList: [91, 90]
      },
      {
        days: 7,
        scoreTypeList: [92, 93]
      },
      {
        days: 7,
        scoreTypeList: [94, 95]
      },
      {
        days: 7,
        scoreTypeList: [96, 97]
      },
      {
        days: 7,
        scoreTypeList: [98, 99]
      }
    ]
    // 循环请求参数
    for (const params of paramsList) {
      const data = await fetchScoreData(params)
      // 处理数据
      scoreData.send({
        data,
        action: "inspect"
      })
    }
  }

  // 数据显示对话框点击显示
  const handleShowDetailModal = () => {
    setShowDetailModal(true)
  }

  // 数据显示对话框关闭方法
  const handleClose = () => {
    setShowDetailModal(false)
  }

  // 数据清空方法
  const handleClear = () => {
    scoreData.send({
      action: "clear"
    })
  }

  useEffect(() => {
    const rate = scoreData.data?.rate || "0"
    // 数据完整率
    setDataCompleteRate(rate)
    // 异常信息记录 对比更新日期
    // 评分日期
    const scoreDate = scoreData.data?.scoreDate || ""
    // 细节日期
    const detailDate = scoreData.data?.detailDate || ""
    const isCurrentDate = (date: string) => {
      return moment(date).isSame(moment(), "date")
    }
    // 判断是否有和当前日期相同
    // if (scoreDate === "" && detailDate === "") {
    //   // 没有日期记录
    //   setExceptionTxt("没有数据记录")
    // } else if (!isCurrentDate(scoreDate) && !isCurrentDate(detailDate)) {
    //   // 两个日期都是非当天，提示异常信息
    //   setExceptionTxt("当前数据非当天数据,原因:[平台未更新]")
    // } else if (!moment(scoreDate).isSame(moment(detailDate), "date")) {
    //   // 两个数据日期不一致，提示异常信息
    //   setExceptionTxt("当前数据不同步,原因:[部分数据未更新]")
    // } else {
    //   setExceptionTxt("")
    // }
  }, [scoreData.data])

  return (
    <ThemeProvider>
      <StyleProvider container={document.getElementById(HOST_ID).shadowRoot}>
        {userLogin ? (
          <div
            className={
              "dy-shop-score-tool-wrapper wx-shop-score-tool-wrapper-fixed"
            }>
            <div className={"button-item"} onClick={handleShowDetailModal}>
              <FormOutlined />
            </div>
            {/*文字描述*/}
            <div className={"button-text"}>
              <span>评分数据</span>
            </div>
            {/*数据完整度*/}
            <div className={"button-tip"}>
              <span>{dataCompleteRate}%</span>
            </div>
          </div>
        ) : null}
        <DyShopScoreDataDetailModal
          shopType={"wx"}
          keys={scoreData?.data?.keysList}
          showDetailModal={showDetailModal}
          handleClose={handleClose}
          dataObject={scoreData?.data?.data}
          dataCompleteRate={dataCompleteRate}
          exceptionTxt={exceptionTxt}
          handleClear={handleClear}
          handleCapture={handleCaptureData}
        />
      </StyleProvider>
    </ThemeProvider>
  )
}

export default WxShopScoreToolbar
